#! /usr/bin/python
# -*- coding: utf-8 -*-2
#######################################################################################
#                                                                                     #
#    File: main.py                                                                    #
#    Part of stage1st-cheater                                                         #
#    Home: http://stage1st-cheater.googlecode.com                                     #
#                                                                                     #
#    The MIT License                                                                  #
#                                                                                     #
#    Copyright (c) 2010-2011 <araya.akashic@gmail.com>                                #
#                                                                                     #
#    Permission is hereby granted, free of charge, to any person obtaining a copy     #
#    of this software and associated documentation files (the "Software"), to deal    #
#    in the Software without restriction, including without limitation the rights     #
#    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell        #
#    copies of the Software, and to permit persons to whom the Software is            #
#    furnished to do so, subject to the following conditions:                         #
#                                                                                     #
#    The above copyright notice and this permission notice shall be included in       #
#    all copies or substantial portions of the Software.                              #
#                                                                                     #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR       #
#    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,         #
#    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE      #
#    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER           #
#    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,    #
#    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN        #
#    THE SOFTWARE.                                                                    #
#                                                                                     #
#######################################################################################
'''
Created on May 14, 2011

@author: flyxian
'''
import time
import os
import signal
import random

import urllib2

import threading
import thread


import browser_bogus
import daily_job
import online_keeper

from daemonize import daemonize

from user_agent_lib import get_random_user_agent

VERSION = "1.6.0"

daily_job_threads = []
online_keeper_threads = []

   

class Daily_Job_Worker(threading.Thread):
    def __init__(self, username, passwd):
        threading.Thread.__init__(self)
        self.browser = browser_bogus.Browser(username, passwd, get_random_user_agent())
        self.setDaemon(True)
        self.stopevent = threading.Event()
        
    def run(self):
        while not self.stopevent.isSet():
            daily_job._perform_cheating(self.browser)
            time.sleep(daily_job.delay)
            
    def join(self, timeout=0):
        self.stopevent.set()
        threading.Thread.join(self, timeout)
        
#class OnlineKeeperWorker(threading.Thread):
#    def __init__(self, username, passwd):
#        super(OnlineKeeperWorker, self).__init__()
#        self.setDaemon(True)
#        self.browser = browser_bogus.Browser(username, passwd, get_random_user_agent())
#    
#    def login(self):
#        try:
#            online_keeper.login(self.browser)
#            print "Online Keeper started for %s" % self.browser.username
#        except online_keeper.LoginFailed:
#            print "Online Keeper Login Failed for %s" % self.browser.username
#        except urllib2.URLError:
#            print "Failed to connect to host. Please check your Internet connection"
#        except urllib2.HTTPError err:
#            print "Request to host failed, code: %d" % err.code
#        except:
#            pass
#        
#    def refresh(self):
#        try:
#            online_keeper.cheat(self.browser)
#        except:
        
class Online_Keeper_Worker(threading.Thread):
    def __init__(self, username, passwd):
        threading.Thread.__init__(self)
        self.browser = browser_bogus.Browser(username, passwd, get_random_user_agent())
        self.setDaemon(True)
        self.stopevent = threading.Event()
        
    def run(self):
        self.counter = 0
        try:
            online_keeper.login(self.browser)
            print "Online Keeper started for %s" % self.browser.username
            while not self.stopevent.isSet():
                try:
                    online_keeper.cheat(self.browser)
                    print ".",
                except urllib2.URLError:
                    print "Failed to connect to host. Please check your Internet connection"
                except:
                    pass
                self.counter += 1
                if self.counter > 125:
                    online_keeper.time2point(self.browser)
                    self.counter = 0
                time.sleep(random.randint(0, 300) + 300)
                
            online_keeper.logout(self.browser)
        except online_keeper.LoginFailed:
                print "Online Keeper Login Failed for %s" % self.browser.username
        except urllib2.URLError:
            print "Failed to connect to host. Please check your Internet connection"
            
    def join(self, timeout=0):
        self.stopevent.set()
        threading.Thread.join(self, timeout)
        

def read_account(filename="accounts.conf"):
    file = open(filename, "r")
    lines = file.readlines()
    file.close()
    
    daily = 0
    online = 0
    
    for line in lines:
        if line[0] == "#":
            continue
        if line[0] == "}":
            daily = 0
            online = 0
            continue
        if line.find("daily_job") >= 0:
            daily = 1
            continue
        if line.find("online_keeper") >= 0:
            online = 1
            continue
        if line.find(":") > 0:
            words = line.split(":")
            username = words[0].strip(" ")
            passwd = words[1].strip(" \n")
#            print "Account:", username, passwd
            if daily == 1:
                worker = Daily_Job_Worker(username, passwd)
                daily_job_threads.append(worker)
            elif online == 1:
                worker = Online_Keeper_Worker(username, passwd)
                online_keeper_threads.append(worker)
            continue
        
        
#    print daily_job_threads
#    print online_keeper_threads
            
def start_all():    
    for worker in daily_job_threads:
        worker.start()
      
    for worker in online_keeper_threads:
        worker.start()
                
def stop_all():
    for worker in daily_job_threads:
        worker.join()
      
    for worker in online_keeper_threads:
        worker.join()  


is_sigint_up = False
def sigint_handler(signum, frame):
    is_sigint_up = True
    stop_all()
    exit()
   
cwd = os.getcwd()   
def main():
    os.chdir(cwd)
    random.seed()
    signal.signal(signal.SIGINT, sigint_handler)
    signal.signal(signal.SIGTERM, sigint_handler)
    read_account()
    start_all()
    while True:
        time.sleep(1000000)
        
      
if __name__ == "__main__":
    daemonize(stdout="/var/log/stage1st-cheater.log", pidfile="/var/run/stage1st-cheater.pid")
    main()
